import React, { PureComponent } from 'react';
import { message, Form, Input, Divider, Table, Icon, Button } from 'antd';
import { connect } from 'dva';
import SyOrderTableComponent from '../../components/SyOrderTableComponent';
import { SyOrderTableBasicFormComponent } from '../../components/SyOrderTableComponent';
import { hasAuthority } from '../../utils/authority';
import baseStyles from '../../components/SyOrderTableComponent/index.less';
import moment from 'moment';

let source = {
  value: '',
  label: '',
};

@Form.create()
@connect(state => ({
  modelState: state.loanBill,
}))
export default class LoanCreated extends SyOrderTableComponent {

  // 缺省
  _initSortion = { sortField: 'id', sortOrder: 'desc', };
  _initPagination = { pageSize: 20, current: 1, };
  _initCriteriaQuery = { status: 'created', source: source.value };
  _operator = [
    // {
    //   needForm: false,
    //   needConfirm: true,
    //   buttonLabel: 'sdfz打款',
    //   authority: 'xbeautyManagement:loanCreated:batchPayByApu',
    //   buttonType: 'danger',
    //   okType: 'danger',
    //   buttonDisabled: 'none',
    //   confirmTitle: '确认 批量 sdfz 打款？',
    //   handleEvent: () => {
    //     let loanIds = this.state.selectedRows.map(entity => entity.loanId);

    //     const { dispatch } = this.props;
    //     if (loanIds && loanIds.length > 0) {
    //       dispatch({
    //         type: this.state.baseModel + '/xbeautyBatchWithdraw',
    //         payload: {
    //           loanIds: loanIds,
    //           lendType: 'apu',
    //         },
    //         callback: (code, msg) => {
    //           if (code == 200) {
    //             message.success(msg);
    //             this.resetCurrentForm();
    //             dispatch({
    //               type: this.state.baseModel + '/fetch',
    //               payload: {
    //                 ...this._initPagination,
    //                 ...this._initSortion,
    //                 ...this._initCriteriaQuery,
    //                 ...this.state.statusQuery,
    //               }
    //             });
    //           } else {
    //             message.error(msg);
    //           }
    //         },
    //       });
    //     }
    //   },
    // },
    {
      needForm: false,
      needConfirm: true,
      buttonLabel: source.label + '打款',
      authority: 'xbeautyManagement:loanCreated:batchPayByXinghe',
      buttonType: 'danger',
      okType: 'danger',
      buttonDisabled: 'none',
      confirmTitle: '确认 批量 ' + source.label + ' 打款？',
      handleEvent: () => {
        let loanIds = this.state.selectedRows.map(entity => entity.loanId);

        const { dispatch } = this.props;
        if (loanIds && loanIds.length > 0) {
          dispatch({
            type: this.state.baseModel + '/xbeautyBatchWithdraw',
            payload: {
              loanIds: loanIds,
              lendType: source.value,
              source: source.value,
            },
            callback: (code, msg) => {
              if (code == 200) {
                message.success(msg);
                this.resetCurrentForm();
                dispatch({
                  type: this.state.baseModel + '/fetch',
                  payload: {
                    ...this._initPagination,
                    ...this._initSortion,
                    ...this._initCriteriaQuery,
                    ...this.state.statusQuery,
                  }
                });
              } else {
                message.error(msg);
              }
            },
          });
        }
      },
    },
  ];

  initSelection() {
    const { dispatch } = this.props;
    dispatch({
      type: 'loanBill/fetchStatistics',
      payload: {
        userName: '',
        mobile: '',
        withdrawId: '',
        startDate: '',
        endDate: ''
      }
    });

    dispatch({
      type: 'loanBill/fetchGetAutoTransferStatus',
      payload: {
        source: source.value
      },
      callback: (res) => {
        const { swtichBtnConfig } = this.state;
        swtichBtnConfig.checked = res.data == '1' ? true : false;
      }
    });
  }

  componentWillMount() {
    this.initSelection();
    this.setState({
      baseModel: 'loanBill',
      operator: this._operator,
      initPagination: this._initPagination,
      initSortion: this._initSortion,
      initCriteriaQuery: this._initCriteriaQuery,
      needSearch: true,
      needAdd: false,
      needEdit: false,
      needDelete: false,
      needTableColumnsOperator: false,
      needTableCheckbox: true,
      tableBorder: false,
      needTableStatistics: true,
      // defaultExpandAllRows: true,
      statusField: 'status',
      needSwtichBtn: source.value == 'xbeauty' ? true : false,
      swtichBtnConfig: {
        label: '自动打款',
        authority: 'xbeautyManagement:loanCreated:autoPayByXbeauty',
        checked: this.props.modelState.getAutoTransferStatusData == '1' ? true : false,
        onlabel: '开',
        offlabel: '关',
        handleEvent: (val) => {
          const { dispatch } = this.props;
          dispatch({
            type: this.state.baseModel + '/fetchPostAutoTransferSwitch',
            payload: {
              source: source.value,
              status: val ? 1 : 0,
            },
            callback: (code, msg) => {
              if (code == 200) {
                message.success(msg);
                const { swtichBtnConfig } = this.state;
                swtichBtnConfig.checked = !swtichBtnConfig.checked;
                // this.initSelection();
              } else {
                message.error(msg);
              }
            },
          });
        }
      },
      tableScroll: { y: 800 },
      tableColumns: [
        // {
        //   title: '用户ID',
        //   dataIndex: 'userId',
        //   width: 180,
        // },
        {
          title: '订单号',
          dataIndex: 'loanId',
          width: 220,
        },
        {
          title: '客户姓名',
          dataIndex: 'userName',
          width: 200,
        },
        {
          title: '性别',
          dataIndex: 'gender',
          width: 100,
        },
        {
          title: '手机号',
          dataIndex: 'mobile',
          width: 150,
        },
        {
          title: '申请时间',
          dataIndex: 'applyTime',
          width: 250,
          render: (text, record) => <span>{record.applyTime ? moment(record.applyTime).format('YYYY-MM-DD HH:mm') : '/'}</span>,
        },
        {
          title: '借款金额',
          dataIndex: 'loanAmount',
          width: 150,
          render: (text, record) => <span>￥ {record.loanAmount}</span>,
        },
        {
          title: '借款天数',
          dataIndex: 'loanLength',
          width: 120,
        },
        // {
        //   title: '银行卡号',
        //   dataIndex: 'bankCardNum',
        //   width: 180,
        // },
        // {
        //   title: '所属银行',
        //   dataIndex: 'bankName',
        //   // width: 220,
        // },
        // {
        //   title: '开户银行',
        //   dataIndex: 'openBankName',
        //   width: 220,
        // },
        // {
        //   title: '状态',
        //   dataIndex: 'status',
        //   // align: 'left',
        //   fixed: 'right',
        //   width: 150,
        // },
        // {
        //   title: '返回码',
        //   dataIndex: 'itemEndTime',
        //   width: 200,
        // },
        {
          title: '借款次数',
          dataIndex: 'loanTimes',
          // width: 100,
        },
        /* {
           title: '信用报告',
           dataIndex: 'userReport',
           width: 100,
           fixed: 'right',
           render: (text, record) =>
             <a onClick={() => {
               this.setState({ editedEntity: record });
             }}>
               查 看
            </a>,
         },*/
        {
          title: '操作',
          dataIndex: 'operatoer',
          width: 80,
          fixed: 'right',
          render: (text, record) =>
            hasAuthority('xbeautyManagement:loanCreated:pay') &&
            <a onClick={() => {
              this.setState({ editedEntity: record });
              this.handleOperator(true, '放 款', this.payForm, null, this.renderPayForm, record, () => this.onPayClick(record), null, this.renderPayModalFootButton, null)
            }}>
              放 款
            </a>

          ,
        },
      ],
      searchFormItem: [
        {
          name: 'userName',
          label: '姓名',
          placeholder: '姓名',
          type: 'string',
        },
        {
          name: 'mobile',
          label: '手机号',
          placeholder: '手机号',
          type: 'string',
        },
        {
          name: 'startDate',
          label: '起始日期',
          placeholder: '起始日期',
          type: 'dateTime',
          showTime: false,
        },
        {
          name: 'endDate',
          label: '截止日期',
          placeholder: '截止日期',
          type: 'dateTime',
          showTime: false,
        },
        {
          name: 'loanId',
          label: '订单号',
          placeholder: '订单号',
          type: 'string',
        },
        // {
        //   name: 'source',
        //   label: '产品平台',
        //   placeholder: '产品平台',
        //   type: 'select',
        //   showTime: false,
        //   selectOption: { itemName: 'sourceSelectItems', name: 'name', value: 'value' },
        // },
      ],
      repayModalVisible: false,
    });
  }

  onPayClick = (record) => {
    const { dispatch } = this.props;
  };

  renderPayModalFootButton = [
    <Button key="transferFail" type="danger" loading={this.props.modelState.operatorLoading} onClick={() => this.handleTransferEvent(false)}
            style={{ float: 'left' }}
    >
      手动打款失败
    </Button>,
    // {<Button key="transferByYbApu" type="primary" loading={this.props.modelState.operatorLoading} onClick={() => this.handleYbTransferEvent('apu')}
    //         style={{ marginRight: 24 }}
    // >
    //   sdfz打款
    // </Button>,}
    <Button key="transferByYbXBeauty" type="primary" loading={this.props.modelState.operatorLoading} onClick={() => this.handleYbTransferEvent(source.value)}
            style={{ marginRight: 24 }}
    >
      {source.label}打款
    </Button>,
    <Button key="transferSuccess" type="primary" loading={this.props.modelState.operatorLoading} onClick={() => this.handleTransferEvent(true)}>
      手动打款
    </Button>,
  ];

  payFormItem = [
    {
      name: 'remark',
      label: '备注',
      placeholder: '备注',
      type: 'longString',
    },
  ];

  renderPayForm = () => {
    const { form, modelState: { selectItems } } = this.props;
    return (
      <SyOrderTableBasicFormComponent
        ref={this.savePayFormFormRef}
        formItems={this.payFormItem}
        selectItems={selectItems}
      >

      </SyOrderTableBasicFormComponent>
    );
  }

  savePayFormFormRef = (form) => {
    this.payForm = form;
  }


  handleYbTransferEvent = (type) => {
    const { dispatch } = this.props;
    const { editedEntity } = this.state;
    const form = this.payForm;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      let value = {
        loanId: editedEntity.loanId,
        lendType: type,
      };
      if (fieldsValue.remark && fieldsValue.remark.length > 0) {
        value.remark = fieldsValue.remark;
      }

      dispatch({
        type: this.state.baseModel + '/loanManualTransferYb',
        payload: { ...value },
        callback: (code, msg) => {
          if (code == 200) {
            message.success(msg);
            this.resetCurrentForm();
            dispatch({
              type: this.state.baseModel + '/fetch',
              payload: {
                ...this.state.initPagination,
                ...this.state.initSortion,
                ...this.state.initCriteriaQuery,
                ...this.state.statusQuery,
                queryUrl: this.state.queryUrl,
              }
            });
          } else {
            message.error(msg);
          }
        },
      });
    });
  }

  handleTransferEvent = (success) => {
    const { dispatch } = this.props;
    const { editedEntity } = this.state;
    const form = this.payForm;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      if (!success && (!fieldsValue.remark || fieldsValue.remark.length == 0)) {
        form.setFields({
          remark: {
            value: fieldsValue.remark,
            errors: [new Error('手动打款失败必须填写备注'),]
          }
        });
        return;
      }

      let value = {
        loanId: editedEntity.loanId,
        isSuccess: success,
      };
      if (fieldsValue.remark && fieldsValue.remark.length > 0) {
        value.remark = fieldsValue.remark;
      }

      dispatch({
        type: this.state.baseModel + '/loanManualTransfer',
        payload: { ...value },
        callback: (code, msg) => {
          if (code == 200) {
            message.success(msg);
            this.resetCurrentForm();
            dispatch({
              type: this.state.baseModel + '/fetch',
              payload: {
                ...this.state.initPagination,
                ...this.state.initSortion,
                ...this.state.initCriteriaQuery,
                ...this.state.statusQuery,
                queryUrl: this.state.queryUrl,
              }
            });
          } else {
            message.error(msg);
          }
        },
      });
    });
  }


  /* ***************************************************************** */

  constructor(props) {
    switch(props.location.pathname.split('/')[1]) {
      case 'xbeautyManagement':
        source.value = 'xbeauty';
        source.label = '想美';
      break;
      case 'assetsManagementForXflower':
        source.value = 'xflower';
        source.label = '信花花';
      break;
      case 'assetsManagementForUpoint':
        source.value = 'upoint';
        source.label = '有点';
      break;
      default:
      break;
    }
    super(props);
  }

  componentDidMount() {
    super.componentDidMount();
  }

}
